import { NotificationOutlined } from '@ant-design/icons'
import { useBoolean } from '@gnlab/utils/env-react'
import { message, Button, Input } from 'antd'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import type { GroupContact } from '@/services/contact-types/groups'
import './index.module.less'

export default function GroupNotice(props: { group: GroupContact }) {
  const { group } = props
  const [showing, show, hide] = useBoolean(false)

  return <>
    <div className="tool" onClick={show}>
      <NotificationOutlined />
      <div className="tool-name">群公告</div>
    </div>

    <EditModal styleName="group-notice" title="发送群公告" open={showing} onCancel={hide}>
      {showing ? <Content group={group} onClose={hide} /> : null}
    </EditModal>
  </>
}

const Content = function Content(props: { group: GroupContact; onClose: () => void }) {
  const { group, onClose } = props

  const [text, setText] = useState('')

  const [submitting, setSubmitting] = useState(false)
  const submit = useCallback(async () => {
    setSubmitting(true)
    const res = await services.groups.updateNotice(text, [group])
    if (res.success) {
      void message.success('群公告发送成功')
      onClose()
    } else {
      void message.warning(`群公告发送失败：${res.error}`)
    }
    setSubmitting(false)
  }, [text, group, onClose])

  return <>
    <main>
      <Input.TextArea
        autoFocus
        autoSize={{ minRows: 6, maxRows: 10 }}
        placeholder="在此输入群公告"
        onChange={e => setText(e.target.value)}
      />
      <div styleName="tips">仅群主和群管理员可成功发布群公告</div>
    </main>
    <footer>
      <Button onClick={onClose}>取消</Button>
      <Button type="primary" onClick={submit} disabled={!text} loading={submitting}>
        发送
      </Button>
    </footer>
  </>
}
